package com.jf.docsify.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jf.docsify.common.exception.DocsifyException;
import com.jf.docsify.common.utils.Resp;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;

/**
 * Description:
 *
 * @author chenwr
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本           修改人       修改日期         修改内容
 * 2022/7/26.1       chenwr    2022/7/26           Create
 * </pre>
 * @date 2022/7/26
 */
public class ErrorInterceptor implements Interceptor {

    private static Logger log = LoggerFactory.getLogger(ErrorInterceptor.class);

    @Override
    public void intercept(Invocation inv) {
        try {
            inv.invoke();
        } catch (Exception e) {
            String actionKey = inv.getActionKey();
            log.error(e.getMessage(), e);
            boolean instanceofDocsifyException = DocsifyException.isInstanceof(e);
            String msg;
            if (instanceofDocsifyException) {
                msg = ((DocsifyException) e).getMsg();
            } else {
                msg = e.getMessage();
            }
            if ("/docs/mdRoute".equals(actionKey)) {
                inv.getController().renderText("# 错误\n > " + msg + ".\n");
                return;
            }
            Resp.error(msg).done(inv.getController());
        }
    }
}